﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using PSE.Deployment.BuildManager.Tools;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Configuration;

namespace UpdateReferencesApp
{
    public partial class UpdateReferencesForm : Form, ILog
    {
        StreamWriter _textLog;
        Dictionary<string, string> _versions = new Dictionary<string, string>();

        private static TeamFoundationServer tfs = null;
        private static VersionControlServer versionControlServer = null;
        private static Workspace workspace = null;

        public UpdateReferencesForm()
        {
            InitializeComponent();

            tfs = TeamFoundationServerFactory.GetServer(ConfigurationManager.AppSettings["TeamFoundationServer"]);
            versionControlServer = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
            workspace = versionControlServer.GetWorkspace(ConfigurationManager.AppSettings["TeamFoundationWorkspace"]);
        }

        private bool ValidateInput()
        {
            if (String.IsNullOrEmpty(txtDirectory.Text))
            {
                MessageBox.Show("Favor informar o diretório contendo os projetos a serem alterados.", "ATENÇÃO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtDirectory.Focus();
                return false;
            }

            if (!Directory.Exists(txtDirectory.Text))
            {
                MessageBox.Show("Diretório inválido.", "ATENÇÃO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtDirectory.Focus();
                return false;
            }

            if (cboPseVersion.SelectedIndex < 0)
            {
                MessageBox.Show("Favor selecionar a versão do PSE a ser utilizada.", "ATENÇÃO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboPseVersion.Focus();
                return false;
            }

            return true;
        }

        private void btnDirectory_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowNewFolderButton = false;
            folderBrowserDialog1.ShowDialog();
            if (!String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
            {
                txtDirectory.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void UpdateReferencesForm_Load(object sender, EventArgs e)
        {
            XDocument document = XDocument.Load("config.xml");


            var directoryQuery = from c in document.Descendants()
                                 where c.Name.LocalName.Equals("DefaultDirectory")
                                 select (XElement)c;

            XElement directory = (XElement)directoryQuery.First();
            txtDirectory.Text = directory.Value;

            var versionsQuery = from c in document.Descendants()
                                where c.Name.LocalName.Equals("PSEVersions")
                                select (XElement)c;

            XElement versions = (XElement)versionsQuery.First();
            foreach (XElement element in versions.Elements())
            {
                if (element.Name.LocalName.Equals("Version"))
                {
                    XAttribute nameAttribute = element.Attribute("name");
                    XAttribute tokenAttribute = element.Attribute("token");

                    _versions.Add(nameAttribute.Value, tokenAttribute.Value);

                    cboPseVersion.Items.Add(nameAttribute.Value);
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }

            btnDirectory.Enabled = false;
            btnStart.Enabled = false;

            System.Diagnostics.Stopwatch timeElipsed = new System.Diagnostics.Stopwatch();
            timeElipsed.Start();
            string[] versionArray = cboPseVersion.Text.Split('.');
            Version version = new Version(
                Int32.Parse(versionArray[0]),
                Int32.Parse(versionArray[1]),
                Int32.Parse(versionArray[2]),
                Int32.Parse(versionArray[3]));

            _textLog = System.IO.File.CreateText(string.Format(@"C:\logreferenceUpdateLog{0}.txt", DateTime.Now.ToString("ddMMyyhhmmss")));

            SetMessageLog("Alterando arquivos...");

            UpdateProjectReferences updater = new UpdateProjectReferences();
            updater.UpdatingFile += new Action<string>(UpdatingFile);
            updater.Log = this;
            updater.UpdateDirectory(version, _versions[version.ToString()], txtDirectory.Text);

            UpdateConfigReferences config = new UpdateConfigReferences(version, txtDirectory.Text);
            config.UpdatingFile += new Action<string>(UpdatingFile);
            config.Log = this;
            config.BeginUpdate();
            timeElipsed.Stop();
            SetMessageLog("Total de Milisegundos: " + timeElipsed.ElapsedMilliseconds.ToString());
            _textLog.Close();

            btnDirectory.Enabled = true;
            btnStart.Enabled = true;
        }

        void UpdatingFile(string file)
        {
            workspace.PendEdit(file);   
        }

        public void SetMessageLog(string message)
        {
            lblLog.Text = message;
            _textLog.WriteLine(message);
        }

        public void SetErrorLog(string message)
        {
            lblLog.Text = message;
            _textLog.WriteLine(message);
        }
    }
}
